/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ita.model.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Abraao
 */
public class GenericDAO<T> {
    final private SessionFactory factory;
    final private Class<T> classe;

    public GenericDAO(SessionFactory factory, Class<T> classe) {
        this.factory = factory;
        this.classe = classe;
    }
    
    private Session getSession() {
        return factory.getCurrentSession();
    }

    public void insert(final T t) {
        Session sess = getSession();
        try{
            sess.beginTransaction();
            sess.save(t);
            sess.getTransaction().commit();
        }
        catch(Exception E){}
        finally{
            if(sess.isOpen())
                sess.close();
        }
    }
    
    public void remove(final T t) {
        Session sess = getSession();
        try
        {
            sess.beginTransaction();
            sess.delete(t);
            sess.getTransaction().commit();
        }
        catch(Exception E)
        {    
        }
        finally{
            if(sess.isOpen())
                sess.close();
        }
    }
    public T searchById(final int id) {
        Session sess = getSession();
        T t = null;
        try
        {
            sess.beginTransaction();
            t = (T)sess.load(classe, id);
            sess.getTransaction().commit();
            return t;
        }
        catch(Exception E){}
        finally{
            if(sess.isOpen())
                sess.close();
            return t;
        }
    }
    public List<T> listAll(final int id) {
        Session sess = getSession();
        List<T> t = new ArrayList<T>();
        try
        {
            sess.beginTransaction();
            t = sess.createCriteria(classe).list();
            sess.getTransaction().commit();
            return t;
        }
        catch(Exception E){}
        finally{
            if(sess.isOpen())
                sess.close();
            return t;
        }
    }
   
        
}
